<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button type="success" size="small" @click="handleDownload">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog =true">新增员工</el-button>
        </template>
      </page-tools>

      <!-- 员工列表 -->
      <el-card style="margin-top: 10px;">
        <!--  -->
        <el-table border :data="employeesList" :default-sort="{prop :'formOfEmployment',order:'ascending'}">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template slot-scope="scope">
              <!-- <img class="staffPhoto" :src="scope.row.staffPhoto"> -->
              <ImageHolder
                class="staffPhoto"
                :src="scope.row.staffPhoto"
              />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" :formatter="formatter" label="聘用形式" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间">
            <template slot-scope="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>

        <!-- 底部分页 -->
        <el-pagination
          :current-page="query.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />

        <el-dialog
          title="提示"
          :visible.sync="showDialog"
          width="50%"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="closeDialog"
        >
          <EmpDialog
            ref="addEmpt"
            @close="showDialog = false"
            @update-list="updateList"
          />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './empDialog.vue'
import dayjs from 'dayjs'
export default {
  components: {
    EmpDialog
  },
  filters: {
    // 格式化入职日期的方法
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10// 每页条数
      },
      total: 0, // 总条数
      employeesList: [], // 员工列表数据
      showDialog: false // 是否开启弹框
    }
  },
  created() {
    // 调用获取员工列表的方法
    this.getEmployeeList()
  },
  methods: {
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      // console.log(res)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    },

    // 格式化聘用形式
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未知'
    },

    // 删除员工
    async delEmp(id) {
      const confirmRes = await this.$confirm('真的要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // console.log(confirmRes)

      if (confirmRes === 'cancel') return this.$message('你取消了删除')

      const res = await delEmployee(id)

      if (this.employeesList.length === 1) {
        this.query.page--
      }

      this.$message.success(res.message)

      this.getEmployeeList()
    },

    // 刷新列表,关闭弹框
    updateList() {
      this.showDialog = false
      this.getEmployeeList()
    },

    // 监听弹框关闭
    closeDialog() {
      this.$refs.addEmpt.resetForm()
    },

    // 格式化后端返回的数据
    transData(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const headerArr = Object.keys(rows[0])

      const header = headerArr.map(item => {
        return map[item]
      })

      const data = rows.map(item => {
        return Object.values(item)
      })

      return { header, data }
    },

    // 导出excel
    async handleDownload() {
      const res = await getEmployeeList(this.query)
      const excelObj = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工信息', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    }
  }
}

</script>

   <style lang="scss" scoped>
   .staffPhoto{
     width: 100px;
     height: 100px;
     border-radius: 50%;
   }
    .el-pagination {
    text-align: center;
    margin-top: 10px;
    }
   </style>

